<?php

namespace app\job;

use app\model\Config;
use app\model\GoodsOrders;
use app\model\PointGoodsOrders;
use app\model\TrainOrders;
use app\model\TrainSchoolLevelVipTrainerClass;
use app\model\User;
use app\tool\Http;
use app\tool\Random;
use Exception;
use GuzzleHttp\Client;
use TCPDF;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\queue\Job;

class Task
{
	

	public function fire(Job $job, $data)
	{
		
		$rt = $this->doJob($data);
		if ($rt) {
			$job->delete();
			return true;
		}
		
		// 重试三次失败
			if ($job->attempts() >= 3) {
				$job->release(60*60*24);
				return false;
			}
		
		//执行失败10S后重试
		$job->release(10);
		
	}
	
	public function doJob($data)
	{
		try {
			if (array_key_exists('action', $data)) {
				//超时系统自动操作
				switch ($data['action']) {
					case 'goods_order_timeout':
						//订单超时取消
						$order_id = $data['order_id'];
						$row = GoodsOrders::findOrFail($order_id);
						if ($row->pay_status == 1) {
							$row->pay_status = 5;
							$row->save();
							//恢复库存
							foreach ($row->detail as $item){
								$item->spec->sku += $item->num;
								$item->together(['spec'])->save();
							}
						}
						break;
					case 'point_goods_order_timeout':
						//订单超时取消
						$order_id = $data['order_id'];
						$row = PointGoodsOrders::findOrFail($order_id);
						if ($row->pay_status == 1) {
							$row->pay_status = 5;
							$row->save();
							//恢复库存
							foreach ($row->detail as $item){
								$item->spec->sku += $item->num;
								$item->together(['spec'])->save();
							}
						}
						break;
					case 'vip_expire':
						$user_id = $data['user_id'];
						$user = User::findOrFail($user_id);
						if ($user->vip_expiretime <= time()) {
							//已过期
							$user->level = 0;
							$user->save();
						}
						break;
					case 'vip_expire_warn':
						$user_id = $data['user_id'];
						$user = User::findOrFail($user_id);
						if ($user->vip_expiretime >= time() && $user->vip_expiretime - time() < 7*24*60*60) {
							//不足7天
							//发送短信
							$username = '13592592467';
							$password = md5('lfl123456' . date('Y-m-d H:i:s'));
							$content = "【美人港垂钓园】您的会员即将过期，请及时续费。";
							Http::post('http://api.sms1086.com/Api/Sendutf8.aspx', [
								'username' => $username,
								'password' => $password,
								'content' => $content,
								'mobiles' => $user->mobile,
								'timestamp' => date('Y-m-d H:i:s'),
								'f' => '1'
							]);
						}
						break;
				}
			}
		} catch (ModelNotFoundException $e) {
			dump('找不到数据');
			return true;
		} catch (Exception $e) {
			dump($e->getMessage());
			dump($e->getLine());
			return false;
		}
		return true;
	}
	
	
}
